﻿CREATE PROCEDURE [dbo].[proc_Company_Range_Update]
	(
		@UserName nvarchar(50),
		@EName nvarchar(50),
		@UpName nvarchar(50),
		@UpDate datetime,
		@CompanyList nvarchar(500),
		@Id int,
		@TId uniqueidentifier,
		@IsAll bit
	)
AS
begin

	--获取公司ID
	Declare @CompanyId int
	Select @CompanyId=CompanyId From Employee Where UserName=@UserName
	
	--修改主表数据
	Update Company_RangeUsers Set
	UserName=@UserName,EName=@EName,CompanyId=@CompanyId,UpName=@UpName,[UpDate]=@UpDate,IsAll=@IsAll Where TId=@TId
	
	--删除从表数据
	Delete From Company_Range Where ParentId=@Id
	
	--插入从表数据
	declare @ParentId int,@i int,@Sort int
	Select @ParentId=@Id
	Set @i=0
	while(@i<len(@CompanyList))
	begin
		if(substring(@CompanyList,@i,charindex(',',@CompanyList,@i)-@i)=@CompanyId)
			begin
				Set @Sort=1
			end
		else
			begin
				Set @Sort=2
			end
		Insert Into Company_Range(ParentId,CompanyId,UserName,Sort)Values(@ParentId, substring(@CompanyList,@i,charindex(',',@CompanyList,@i)-@i),@UserName,@Sort)
		Set @i=charindex(',',@CompanyList,@i)+1
	end
end
	RETURN